package com.hongkuncheng.cms.controller.index;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.CookieHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.helper.StringHelper;
import com.hongkuncheng.cms.helper.SystemHelper;
import com.hongkuncheng.cms.model.Form;
import com.hongkuncheng.cms.model.FormData;
import com.hongkuncheng.cms.model.FormDataAtisfaction;
import com.hongkuncheng.cms.model.FormDataValue;
import com.hongkuncheng.cms.model.FormField;
import com.hongkuncheng.cms.model.Member;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

@Controller
@Transactional
@RequestMapping("form")
public class IformController extends BaseController {

    // 表单列表
    @RequestMapping
    public String index() throws Exception {
        int formId = Integer.parseInt(request.getParameter("formid"));
        Form form = factorySession.get(Form.class, formId);
        request.setAttribute("form", form);
        List<FormField> formfields = factorySession.createCriteria(FormField.class)
                .add(Restrictions.eq("form.id", formId))
                .add(Restrictions.eq("listshow", true)).list();
        request.setAttribute("formfields", formfields);
        Criteria criteriaFormdatas = factorySession.createCriteria(FormData.class)
                .add(Restrictions.eq("form.id", formId));
        int state = request.getParameter("state") == null ? -1 : Integer.parseInt(request.getParameter("state"));
        if (state == 0) criteriaFormdatas.add(Restrictions.isNull("result"));
        else if (state == 1) criteriaFormdatas.add(Restrictions.isNotNull("result"));
        request.setAttribute("state", state);
        Member member = (Member) request.getSession().getAttribute("member");
        System.out.println("member:" +  member.getId());
        List<FormData> formdatas = criteriaFormdatas.add(Restrictions.eq("member.id", member.getId()))
                .addOrder(Order.desc("subtime")).list();
        System.out.println("formdatas.size() :" + formdatas.size());
        if (formdatas.size() == 0) {
            response.sendRedirect("/form/submit?formid=" + formId + "&noreturn=1");
            return null;
        } else {
            request.setAttribute("formdatas", formdatas);
            frontpageCommon();
            request.setAttribute("viewcontentpath", webinfo.getTemplate() + "/form.html");
            return view();
        }
    }

    // 表单提交
    @RequestMapping("submit")
    public String submit() {
        int formId = Integer.parseInt(request.getParameter("formid"));
        Form form = factorySession.get(Form.class, formId);
        request.setAttribute("form", form);
        StringBuilder notnullScript = new StringBuilder();
        for (FormField formfiled : form.getFormFields())
            if (formfiled.isNotnull()) notnullScript.append("checknull(\"" + formfiled.getName() + "\", \"" +
                    formfiled.getTitle() + "\") && ");
        notnullScript.append("checknull(\"vcode\", \"验证码\")");
        request.setAttribute("notnullscript", notnullScript);
        request.setAttribute("noreturn", request.getParameter("noreturn") != null);
        frontpageCommon();
        request.setAttribute("viewcontentpath", webinfo.getTemplate() + "/form_submit.html");
        return view();
    }

    // 表单提交
    @RequestMapping("submitdo")
    @ResponseBody
    public void submitdo() throws Exception {
        String checkcode = CookieHelper.GetCookie(request, "checkcode", true);
        if (checkcode == null) {
            PageHelper.alertAndRedirect("验证码加载失败", "/member/login");
        } else {
            String vcode = request.getParameter("vcode");
            if (!vcode.equalsIgnoreCase(checkcode)) {
                PageHelper.alertAndGoBack("验证码错误，请重新输入。");
            } else {
                int formId = Integer.parseInt(request.getParameter("formid"));
                Form form = factorySession.get(Form.class, formId);
                FormData formdata = new FormData();
                formdata.setForm(form);
                formdata.setMember((Member) request.getSession().getAttribute("member"));
                formdata.setSubtime(new Date());
                formdata.setIpaddress(SystemHelper.getIpAddr(request));
                factorySession.save(formdata);
                for (FormField formfield : form.getFormFields()) {
                    FormDataValue value = new FormDataValue();
                    value.setContents(StringHelper.escapeXss(request.getParameter(formfield.getName())));
                    value.setFormData(formdata);
                    value.setFormField(formfield);
                    factorySession.save(value);
                }
                response.sendRedirect("/form/?formid=" + formId);
            }
            CookieHelper.RemoveCookie(response, "checkcode");
        }
    }

    // 表单详细
    @RequestMapping("detail")
    public String detail() throws Exception {
        int formId = Integer.parseInt(request.getParameter("formid"));
        Form form = factorySession.get(Form.class, formId);
        request.setAttribute("form", form);
        int formdataId = Integer.parseInt(request.getParameter("formdataid"));
        FormData formdata = factorySession.get(FormData.class, formdataId);
        request.setAttribute("formdata", formdata);
        StringBuilder formnames = new StringBuilder(); // 控件name集合
        StringBuilder formvalues = new StringBuilder(); // 控件值集合
        for (FormDataValue value : formdata.getFormDataValues()) {
            if (value.getContents() != null) {
                formnames.append(",\"" + value.getFormField().getName() + "\"");
                formvalues.append(",\"" + value.getContents() + "\"");
            }
        }
        if (formnames.length() > 0) {
            formnames.deleteCharAt(0);
            formvalues.deleteCharAt(0);
        }
        request.setAttribute("formnames", formnames);
        request.setAttribute("formvalues", formvalues);
        List<FormDataAtisfaction> atisfactions = factorySession.createCriteria(FormDataAtisfaction.class)
                .list();
        request.setAttribute("atisfactions", atisfactions);
        frontpageCommon();
        request.setAttribute("viewcontentpath", webinfo.getTemplate() + "/form_detail.html");
        return view();
    }

    // 表单评价
    @RequestMapping("evaluate")
    @ResponseBody
    public void evaluate() throws Exception {
        int formId = Integer.parseInt(request.getParameter("formid"));
        int formdataId = Integer.parseInt(request.getParameter("formdataid"));
        FormData formdata = factorySession.load(FormData.class, formdataId);
        int atisfactionId = Integer.parseInt(request.getParameter("atisfactionid"));
        FormDataAtisfaction atisfaction = factorySession.load(FormDataAtisfaction.class, atisfactionId);
        formdata.setFormDataAtisfaction(atisfaction);
        formdata.setEvaluate(request.getParameter("evaluate"));
        response.sendRedirect("/form/?formid=" + formId);
    }

    // 表单删除
    @RequestMapping("deletedata")
    @ResponseBody
    public void deletedata() throws Exception {
        int formId = Integer.parseInt(request.getParameter("formid"));
        int formdataId = Integer.parseInt(request.getParameter("formdataid"));
        FormData formdata = factorySession.load(FormData.class, formdataId);
        Member member = (Member) request.getSession().getAttribute("member");
        if (formdata.getMember().getId() == member.getId()) {
            factorySession.delete(formdata);
            response.sendRedirect("/form/?formid=" + formId);
        } else {
            print("delete error!");
        }
    }
}
